#Copyright Ken Faulkner 2007.
import wx
import wx.lib.scrolledpanel as scrolled

from configobj import ConfigObj
from Common.logRoutine import *
import traceback
from Framework.Converter.MpegEncoder import MpegEncoder
import os
import os.path

class ConfigNotebook(wx.Notebook):
  def __init__(self, parent, id):
    wx.Notebook.__init__(self, parent, id, size=(600,600))

    self.home_dir = os.path.join( os.getenv("HOME"), ".bbc")

    self.userConfig = ConfigObj( os.path.join( self.home_dir, "user.cfg" ) )
    self.config = ConfigObj( os.path.join( self.home_dir, "bbc.cfg" ) )
    
    self.log = getLogger()
    
    # TextCtrl list.
    self.searchFields = []

    self.encodingLevel = int( self.userConfig.get( 'EncodingLevel', MpegEncoder.LEVEL_CD ) )
      
    self.createPages()
    

  def createSearchPage( self ):
    """
    Create the search config page.
    """
    
    self.log.info("ConfigNotebook::createSearchPage start")
    #win = wx.Panel(self, -1, size=(600,600))
    win = scrolled.ScrolledPanel(self, -1, size=(400,400))
     
    try:

      win.SetupScrolling()
      
      vSizer = wx.BoxSizer(wx.VERTICAL)
      win.SetSizer( vSizer )
      
      maxSearches = int( self.config['BBC']['MaxSearchTerms'] )
    
      searchTerms = self.userConfig['SearchTerms']
      
      l = len( searchTerms )
      
      for i in xrange( maxSearches ):
        box = wx.BoxSizer(wx.HORIZONTAL)
        
        label = wx.StaticText( win, -1, "Search #" + str( i+1 ) )
        box.Add( label, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
        
        if i < l:
          val = searchTerms[i] 
        else:
          val = ""
          
        text = wx.TextCtrl( win , -1, val , size=(100,-1))
        self.searchFields.append( text )
        box.Add(text, 1, wx.ALIGN_CENTRE|wx.ALL, 5)
        vSizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)

    except:
       self.log.error("ConfigNotebook::createSearchPage ex " +traceback.format_exc() )
   
    return win


  def createMiscPage( self ):
    """
    Create the misc config page.
    """
    
    self.log.info("ConfigNotebook::createMiscPage start")
    win = scrolled.ScrolledPanel(self, -1, size=(400,400))
     
    try:

      win.SetupScrolling()
      
      vSizer = wx.BoxSizer(wx.VERTICAL)
      win.SetSizer( vSizer )

      
      ############
      # download dir.
      downloadSizer = wx.BoxSizer( wx.HORIZONTAL )
      
      label1 = wx.StaticText( win, -1, "Download Folder:" )
      downloadSizer.Add( label1, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
      
      downloadText = self.userConfig['DownloadDir']
      self.downloadDir = wx.TextCtrl( win , -1, downloadText , size=(200,-1))
      downloadSizer.Add( self.downloadDir, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
 
      dirImg = wx.Bitmap("images/folder-open.png", wx.BITMAP_TYPE_PNG)
      id = wx.NewId()
      dirButton = wx.BitmapButton( win, id, dirImg )
      dirButton.SetToolTipString("Select download folder.")
      
      self.Bind( wx.EVT_BUTTON, self.startDirSelect, dirButton)

      downloadSizer.Add( dirButton, 0, wx.ALIGN_CENTRE|wx.ALL,5)
      
      vSizer.Add( downloadSizer )


      ############
      # mplayer binary.
      mplayerSizer = wx.BoxSizer( wx.HORIZONTAL )
      
      label1 = wx.StaticText( win, -1, "MPlayer location:" )
      mplayerSizer.Add( label1, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
      
      mplayerText = self.userConfig['MPlayerBinary']
      self.mplayerBinary = wx.TextCtrl( win , -1, mplayerText , size=(200,-1))
      mplayerSizer.Add( self.mplayerBinary, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
 
      dirImg = wx.Bitmap("images/folder-open.png", wx.BITMAP_TYPE_PNG)
      id = wx.NewId()
      dirButton = wx.BitmapButton( win, id, dirImg )
      dirButton.SetToolTipString("Select MPlayer location.")
      
      self.Bind( wx.EVT_BUTTON, self.startMPlayerSelect, dirButton)

      mplayerSizer.Add( dirButton, 0, wx.ALIGN_CENTRE|wx.ALL,5)
      
      vSizer.Add( mplayerSizer )

      ############
      # lame binary.
      lameSizer = wx.BoxSizer( wx.HORIZONTAL )
      
      label1 = wx.StaticText( win, -1, "Lame location:" )
      lameSizer.Add( label1, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
      
      lameText = self.userConfig['LameBinary']
      self.lameBinary = wx.TextCtrl( win , -1, lameText , size=(200,-1))
      lameSizer.Add( self.lameBinary, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
 
      dirImg = wx.Bitmap("images/folder-open.png", wx.BITMAP_TYPE_PNG)
      id = wx.NewId()
      dirButton = wx.BitmapButton( win, id, dirImg )
      dirButton.SetToolTipString("Select Lame location.")
      
      self.Bind( wx.EVT_BUTTON, self.startLameSelect, dirButton)

      lameSizer.Add( dirButton, 0, wx.ALIGN_CENTRE|wx.ALL,5)
      
      vSizer.Add( lameSizer )
      
      #############
      # Max downloads.
      maxThreadsSizer = wx.BoxSizer( wx.HORIZONTAL )
      label2 = wx.StaticText( win, -1, "Max concurrent downloads:" )
      maxThreadsSizer.Add( label2, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
      
      maxThreads = self.userConfig['NoDownloadThreads']
      self.maxThreads = wx.TextCtrl( win , -1, maxThreads , size=(50,-1))
      maxThreadsSizer.Add( self.maxThreads, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
 
      vSizer.Add( maxThreadsSizer )
      
      ##################
      # encoding quality
      encodingSizer = wx.BoxSizer( wx.HORIZONTAL )
      label3 = wx.StaticText( win, -1, "Encoding quality" )
      encodingSizer.Add( label3, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
      
      # magic no's!!!!
      
      self.cb = wx.ComboBox( win , choices=['Low','Mid','Voice','CD' ], style = wx.CB_DROPDOWN )
      self.cb.SetSelection(  self.encodingLevel )
      
      encodingSizer.Add( self.cb )
      
      self.Bind( wx.EVT_COMBOBOX, self.onCombo )
      
      vSizer.Add( encodingSizer)
      
    except:
       self.log.error("ConfigNotebook::createMiscPage ex " +traceback.format_exc() )
   
    return win
    
  def onCombo( self, evt):
    self.log.debug("Combo evt " + str( evt.GetInt() ) ) 
    #self.userConfig['EncodingLevel'] = evt.GetInt()
    self.encodingLevel = evt.GetInt()
    
        
  def startDirSelect( self, evt):
    
    dlg = wx.DirDialog( self, "Choose the download folder:", style = wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
    if dlg.ShowModal() == wx.ID_OK:
      downloadDir = dlg.GetPath()
      self.downloadDir.SetValue( downloadDir )

  def startMPlayerSelect( self, evt):
    
    dlg = wx.FileDialog( self, "Choose the MPlayer binary location:", style = wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
    if dlg.ShowModal() == wx.ID_OK:
      mplayerBinary = dlg.GetPath()
      self.mplayerBinary.SetValue( mplayerBinary )

  def startLameSelect( self, evt):
    
    dlg = wx.FileDialog( self, "Choose the Lame binary location:", style = wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
    if dlg.ShowModal() == wx.ID_OK:
      lameBinary = dlg.GetPath()
      self.lameBinary.SetValue( lameBinary )      
            
  def createPages( self ):
    """
    Create the various pages of config
    """
    
    self.log.info("ConfigNotebook::createPages start")
    try:
    
      win = self.createSearchPage()
      self.AddPage(win, "Search")

      win = self.createMiscPage()
      self.AddPage(win, "Misc")

    except:
       self.log.error("ConfigNotebook::createPages ex " +traceback.format_exc() )
   
